<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition
	xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui" 
	xmlns:pe="http://primefaces.org/ui/extensions"
	template="/WEB-INF/templates/template.xhtml">
	
<ui:define name="headIncludes">
	<f:event listener="#{vendaBean.initializeForm}" type="preRenderView"/>
</ui:define>
	
	<ui:define name="pageName">Cadastrar Venda</ui:define>
	
	<ui:define name="buttons">
		<p:commandButton value="Salvar" style="height:28px;" action="#{vendaBean.save}" update="@this, messageFormVenda" icon="ui-icon-disk"/>
		<p:commandButton value="Voltar" style="height:28px;" action="#{vendaBean.changeToList}" process="@this" icon="ui-icon-arrowreturnthick-1-w"/>
	</ui:define>
	
	<ui:define name="content">
		<p:panel>
			<div>
				<p:messages id="messageFormVenda" autoUpdate="true"/>
				
				<h:panelGrid columns="5" style="padding:5px;" id="panel1">
					<h:outputText value="Numero da nota" />
					<h:outputText value="Série *" />
					<h:outputText value="Cliente *" />
					<h:outputText value="" />
					<h:outputText value="Data de emissão *" />
					
					<p:inputText style="width:100px;" value="#{vendaBean.currentVenda.numeroNota}" disabled="true"/>
					<p:inputText style="width:100px;" value="#{vendaBean.currentVenda.numeroSerie}" required="true" requiredMessage="Informe o número de série."
						disabled="#{(vendaBean.contasReceber.size() > 0)}" maxlength="20"/>
					<p:autoComplete id="inputCliente" var="cliente" value="#{vendaBean.currentVenda.cliente}"
						itemLabel="#{cliente.nome}" itemValue="#{cliente}" size="50" required="true" requiredMessage="Selecione um cliente."
						converter="clienteConverter" completeMethod="#{vendaBean.getClienteByQuery}"
						disabled="#{(vendaBean.contasReceber.size() > 0)}"/>
					<p:commandButton icon="ui-icon-search" style="height:24px;" immediate="true" actionListener="#{vendaBean.openDialogListCliente}"
						disabled="#{(vendaBean.contasReceber.size() > 0)}" title="Selecionar cliente"/>	
			
					<p:calendar value="#{vendaBean.currentVenda.emissao}" required="true" navigator="true" requiredMessage="Informe a data de emissão." id="inputDataEmissao"
						readonlyInput="true" showButtonPanel="true" locale="pt_BR" pattern="dd/MM/yyyy" style="width:80px;" mindate="#{vendaBean.minDate}" disabled="#{(vendaBean.contasReceber.size() > 0)}"/>
				</h:panelGrid>
				
				<h:panelGrid columns="9" style="padding:5px;" id="panelProduto">
					<h:outputText value="Produto"/>
					<h:outputText value="Unidade"/>
					<h:outputText value=""/>
					<h:outputText value="Quantidade"/>
					<h:outputText value="Valor unitário"/>
					<h:outputText style="padding-left:10px;padding-right:10px;" value="BC ICMS"/>
					<h:outputText style="padding-right:10px;" value="% ICMS"/>	
					<h:outputText style="padding-left:10px;padding-right:10px;" value="Valor ICMS"/>	
					<h:outputText value=""/>
									
					<p:autoComplete id="inputProduto" var="produto" value="#{vendaBean.itemVenda.produto}"
						itemLabel="#{produto.descricao}" itemValue="#{produto}" size="50"
						converter="produtoConverter" completeMethod="#{vendaBean.getProdutoByQuery}"
						disabled="#{(vendaBean.contasReceber.size() > 0)}"
						onkeypress="if (event.keyCode == 13) { event.preventDefault();  $('#btAdicionarItem').click(); }">
						<p:ajax event="itemSelect" process="@this inputProduto" update="inputUnidadeProduto inputItemValor" listener="#{vendaBean.handleProdutoSelected}"/>
					</p:autoComplete>
					
					<p:inputText style="width:80px;" value="#{vendaBean.itemVenda.produto.unidade}" id="inputUnidadeProduto" disabled="true"/>
					
					<p:commandButton icon="ui-icon-search" style="height:24px;" immediate="true" actionListener="#{vendaBean.openDialogListProduto}"
						disabled="#{(vendaBean.contasReceber.size() > 0)}" title="Selecionar produto"/>
						
					<p:inputText style="width:80px;" value="#{vendaBean.itemVenda.quantidade}" id="inputQuantidadeItem"
						disabled="#{(vendaBean.contasReceber.size() > 0)}" maxlength="5"
						onkeypress="if (event.keyCode == 13) { event.preventDefault(); atualizaImpostos(); $('#btAdicionarItem').click(); }">
						<p:ajax event="blur" update="@this" listener="#{vendaBean.handleInputsItemChange}"/>
						<pe:keyFilter regEx="/[\d]/" />
					</p:inputText>
					
					<pe:inputNumber style="width:80px;" value="#{vendaBean.itemVenda.valor}" id="inputItemValor" decimalSeparator="," decimalPlaces="2"  thousandSeparator="."
						disabled="#{(vendaBean.contasReceber.size() > 0)}"  maxValue="1000000"
						onkeypress="if (event.keyCode == 13) { event.preventDefault(); atualizaImpostos(); $('#btAdicionarItem').click(); }">
						<p:ajax event="blur" update="@this" listener="#{vendaBean.handleInputsItemChange}"/>
					</pe:inputNumber>
				
					<h:outputText style="padding-left:10px;" value="#{vendaBean.itemVenda.bcIcms}" id="inputItemBcIcms">
						<f:convertNumber pattern="R$ #,###,##0.00" />
					</h:outputText>
					
					<pe:inputNumber style="width:80px;" decimalPlaces="2" decimalSeparator="," thousandSeparator="."  value="#{vendaBean.itemVenda.percentualIcms}" id="inputItemPercIcms"
						disabled="#{(vendaBean.contasReceber.size() > 0)}" maxValue="100"
						onkeypress="if (event.keyCode == 13) { event.preventDefault(); atualizaIcms(); $('#btAdicionarItem').click(); }">
						<p:ajax event="blur" update="@this" listener="#{vendaBean.handleInputIcmsChange}"/>
					</pe:inputNumber>
					
					<h:outputText style="padding-left:10px;" value="#{vendaBean.itemVenda.valorIcms}" id="inputItemValorIcms">
						<f:convertNumber pattern="R$ #,###,##0.00" />
					</h:outputText>
					
					<p:commandButton style="height:24px;" icon="ui-icon-plus" actionListener="#{vendaBean.addItemVenda}" disabled="#{(vendaBean.contasReceber.size() > 0)}" id="btAdicionarItem" title="Adicionar item"/>
					
				</h:panelGrid>

				<p:remoteCommand actionListener="#{vendaBean.handleInputsItemChange}" name="atualizaImpostos"/>
				<p:remoteCommand actionListener="#{vendaBean.handleInputIcmsChange}" name="atualizaIcms"/>
				
				<div style="padding-top:10px;">
				  	<p:dataTable emptyMessage="Não há registros"
						id="tableItensVenda" value="#{vendaBean.currentVenda.itensVenda}"
						var="item">						
						<p:columnGroup type="header">  
				            <p:row>
				            	<p:column rowspan="2" headerText="Código" width="25"/>			 
								<p:column rowspan="2" headerText="Produto"/> 
								<p:column rowspan="2" headerText="Qtde." width="40"/>
								<p:column rowspan="2" headerText="V. unit." width="50"/>
								<p:column rowspan="2" headerText="V. total" width="50"/>
								<p:column rowspan="2" headerText="BC ICMS" width="40"/>
								<p:column rowspan="2" headerText="V. ICMS" width="40"/>
								<p:column rowspan="2" headerText="V. IPI" width="40"/>
				                <p:column colspan="1" headerText="Alíquota" /> 
				                <p:column rowspan="2" width="1"/>
				            </p:row>  
				  
				            <p:row>  
				                <p:column headerText="ICMS" width="20"/>  
				            </p:row>  
				        </p:columnGroup>
				        
		            	<p:column style="text-align:center;">  
					    	#{item.produto.id} 
						</p:column>				 
						<p:column>  
					    	#{item.produto.descricao}  
						</p:column> 
						<p:column style="text-align:center;">  
					    	#{item.quantidade}  
						</p:column>
						<p:column style="text-align:center;">  
					    	<h:outputText value="#{item.valor}">
				    			<f:convertNumber pattern="R$ #,###,##0.00" />
				    		</h:outputText> 
						</p:column>
						<p:column style="text-align:center;">  
					    	<h:outputText value="#{item.total}">
				    			<f:convertNumber pattern="R$ #,###,##0.00" />
				    		</h:outputText>		  
						</p:column>
						<p:column style="text-align:center;">  
					    	<h:outputText value="#{item.bcIcms}">
				    			<f:convertNumber pattern="R$ #,###,##0.00" />
				    		</h:outputText>		  
						</p:column>
						<p:column style="text-align:center;">  
					    	<h:outputText value="#{item.valorIcms}">
				    			<f:convertNumber pattern="R$ #,###,##0.00" />
				    		</h:outputText>		  
						</p:column>
					
						<p:column style="text-align:center;">  
					    	<h:outputText value="#{item.valorIcms}">
				    			<f:convertNumber pattern="R$ #,###,##0.00" />
				    		</h:outputText>		  
						</p:column>
						
						<p:column style="text-align:center;">  
					    	<h:outputText value="#{item.percentualIcms}">
				    			<f:convertNumber pattern="#,###,##0.00" />
				    		</h:outputText>		  
						</p:column>
						
						<p:column width="10" style="padding:1px;">  
					    	<p:commandButton icon="ui-icon-trash" actionListener="#{vendaBean.removeItemVenda(item)}" style="height:24px;width:23px;" immediate="true" 
					    		id="btRemoverItem" disabled="#{(vendaBean.contasReceber.size() > 0)}" title="Remover item"/>
						</p:column>
				  	</p:dataTable>
				</div>
				
				<h:panelGrid columns="6" style="padding:5px;" id="panelTotal">
					<h:outputText style="padding-right:15px;" value="BC ICMS"/>
					<h:outputText style="padding-right:15px;" value="Valor ICMS"/>
					<h:outputText value="Total dos produtos"/>
					<h:outputText value="Desconto (%)"/>
					<h:outputText value="Desconto (R$)"/>
					<h:outputText style="padding-left:15px;" value="Total da nota"/>

					<h:outputText style="padding-right:15px;" value="#{vendaBean.currentVenda.bcIcms}" id="outputBcIcms">
						<f:convertNumber pattern="R$ #,###,##0.00" />
					</h:outputText>
					
					<h:outputText style="padding-right:15px;" value="#{vendaBean.currentVenda.valorIcms}" id="outputValorIcms">
						<f:convertNumber pattern="R$ #,###,##0.00" />
					</h:outputText>
					
					<h:outputText value="#{vendaBean.totalItensNota}" id="inputTotalItens">
						<f:convertNumber pattern="R$ #,###,##0.00" />
				    </h:outputText>
				    
					<pe:inputNumber style="width:80px;" value="#{vendaBean.currentVenda.descontoPercentual}" decimalPlaces="2" decimalSeparator="," thousandSeparator="." id="inputDescontoPercent"
						disabled="#{(vendaBean.contasReceber.size() > 0) or (vendaBean.currentVenda.descontoValor != null and vendaBean.currentVenda.descontoValor > 0)}" maxValue="100">
						<p:ajax event="blur" update="@this inputDescontoValor" listener="#{vendaBean.handleInputDescontoPercentChange}"/>
					</pe:inputNumber>
					
					<pe:inputNumber style="width:80px;" value="#{vendaBean.currentVenda.descontoValor}" decimalPlaces="2" decimalSeparator="," thousandSeparator="." id="inputDescontoValor" 
						disabled="#{(vendaBean.contasReceber.size() > 0) or (vendaBean.currentVenda.descontoPercentual != null and vendaBean.currentVenda.descontoPercentual > 0)}" maxValue="100000">
						<p:ajax event="blur" update="@this inputDescontoPercent" listener="#{vendaBean.handleInputDescontoValorChange}"/>
					</pe:inputNumber>
					
					<h:outputText style="padding-left:15px;" value="#{vendaBean.currentVenda.totalNota}" id="inputTotalNota">
						<f:convertNumber pattern="R$ #,###,##0.00" />
				    </h:outputText>
				</h:panelGrid>
				
				<h:panelGrid columns="4" style="padding:5px;" id="panelCondicao">
					<h:outputText value="Condição de pagamento *"/>
					<h:outputText value=""/>
					<h:outputText value=""/>
					<h:outputText value=""/>
									
					<p:autoComplete id="inputCondicao" var="condicao" value="#{vendaBean.currentVenda.condicaoPagamento}"
						itemLabel="#{condicao.condicaoPagamento}" itemValue="#{condicao}" size="50"
						converter="condicaoPagamentoConverter" completeMethod="#{vendaBean.getCondicaoPagamentoByQuery}"
						disabled="#{(vendaBean.contasReceber.size() > 0)}"/>
					<p:commandButton icon="ui-icon-search" style="height:24px;" immediate="true" actionListener="#{vendaBean.openDialogListCondicaoPagamento}"
						disabled="#{(vendaBean.contasReceber.size() > 0)}" title="Selecionar condição de pagamento"/>
					<p:commandButton style="height:24px;" value="Gerar" actionListener="#{vendaBean.gerarContasReceber}" 
						disabled="#{(vendaBean.currentVenda.itensVenda.size() == 0) or (vendaBean.contasReceber.size() > 0)}" id="btGerar" title="Gerar contas a receber"/>
					<p:commandButton style="height:24px;" value="Limpar" id="btLimpar" disabled="#{(vendaBean.currentVenda.itensVenda.size() == 0) or (vendaBean.contasReceber.size() == 0)}" 
						actionListener="#{vendaBean.cleanListContasReceber}" title="Limpar contas a receber"/>
				</h:panelGrid>
				
				<div style="padding-top:10px; margin-left: 10px;">
					<p:dataTable emptyMessage="Não há registros" style="width:500px;" value="#{vendaBean.contasReceber}" 
						var="conta" rowIndexVar="index" id="tableContasReceber">						
						<p:column headerText="Parcela" style="width:100px; text-align:center;">  
					    	<h:outputText value="#{index + 1}"/>  
						</p:column>				 
						<p:column headerText="Vencimento" style="width:100px; text-align:center;">  
					    	<h:outputText value="#{conta.dataVencimento}">
								<f:convertDateTime pattern="dd/MM/yyyy"/>
							</h:outputText>  
						</p:column> 
						<p:column headerText="Valor" style="width:100px; text-align:center;">  
					    	<h:outputText value="#{conta.valor}">
				    			<f:convertNumber pattern="R$ #,###,##0.00" />
				    		</h:outputText>   
						</p:column>
				  	</p:dataTable>
				</div>
			</div>
			<h:panelGrid columns="1" style="padding:5px;">
				<h:outputText value="* Campos obrigatórios" />
			</h:panelGrid>
		</p:panel>				
	</ui:define>
	<ui:define name="popups">
		<ui:include src="listCondicaoPagamento.xhtml"/>
		<ui:include src="formCondicaoPagamento.xhtml"/>
		<ui:include src="listFormaPagamento.xhtml"/>
		<ui:include src="formFormaPagamento.xhtml"/>
		<ui:include src="listCliente.xhtml"/>
		<ui:include src="formCliente.xhtml"/>
		<ui:include src="listProduto.xhtml"/>
		<ui:include src="formProduto.xhtml"/>
		<ui:include src="listGrupo.xhtml"/>
		<ui:include src="formGrupo.xhtml"/>
		<ui:include src="listCidade.xhtml"/>
		<ui:include src="formCidade.xhtml"/>
		<ui:include src="listEstado.xhtml"/>
		<ui:include src="formEstado.xhtml"/>
		<ui:include src="listPais.xhtml"/>
		<ui:include src="formPais.xhtml"/>
		
		<p:dialog appendToBody="true" modal="true" closable="false" widgetVar="popupConfirmAddItem"
			width="400" resizable="false" header="Confirmação" height="110">
			<h:form>
				<div style="margin-top: 10px;">
					<h:outputText value="Já existe um item de venda com este produto. Deseja atualizar as informações deste item?"/>
				</div>
				<div align="right" style="margin-top: 15px; margin-bottom: 15px;">
					<p:commandButton value="Confirmar" actionListener="#{vendaBean.confirmAddItem}" oncomplete="popupConfirmAddItem.hide()"/>
					<p:commandButton value="Cancelar" onclick="popupConfirmAddItem.hide()"/>
				</div>		
			</h:form>			
		</p:dialog>
	</ui:define>
</ui:composition>